<template>
  <WidgetContainer :widget-id="config.id">
    <template #bottom>
      <div class="heard-box">
        <el-button type="primary" @click.stop="addColumn" :icon="Plus" circle size="small" />
        <el-button type="info" @click.stop="delColumn" :icon="Minus" circle size="small" />
      </div>
    </template>
    <el-row :class="config.attributes?.cssClass" class="row-container" v-show="!config.attributes.hidden" :gutter="config.attributes.gutter">
      <el-col v-for="(element, index) in config.children" :span="element.attributes.span || 12">
        <WidgetContainer :widget-id="element.id">
          <draggable v-model="element.children" group="form" item-key="id" @add="onAdd" class="col-draggable" :animation="150">
            <template #item="{ element: child, index: childIndex }">
              <component :is="designer.renderComponent(child)" :config="child" />
            </template>
          </draggable>
        </WidgetContainer>
      </el-col>
    </el-row>
  </WidgetContainer>
</template>

<script setup>
import { inject, onMounted } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'

import { ElRow, ElCol } from 'element-plus';
// 注入 designer
const designer = inject('designer')
const widgetList = inject('widgetList')
const selectWidgetId = inject('selectWidgetId')

const onAdd = (evt) => {
    selectWidgetId.value = evt?.item?._underlying_vm_?.id || selectWidgetId.value
};

// 定义 props
const props = defineProps({
  config: {
    type: Object,
    required: true,
    default: () => ({ children: [] }),
  },
});

// 添加列
const addColumn = () => {
  props.config.children.push({
    type: 'col',
    label: '栅格列',
    isContainer: true,
    id: designer.generateUniqueId('col',widgetList.value),
    children: [],
    attributes: {
      span: 12
    }
  });
};

// 删除列
const delColumn = () => {
  if (props.config.children.length > 0) {
    props.config.children.pop();
  }
};

// 初始挂载三个空列（仅首次）
onMounted(() => {
  if (props.config.children.length === 0) {
    addColumn();
    addColumn();
    addColumn();
  }
});
</script>

<style scoped>
.heard-box {
  margin-top: 3px;
}

.row-container {
  min-height: 90px;
  margin: 5px 0;
}

.col-draggable {
  min-height: 90px;
  margin: 1px;
  padding: 5px;
  border: 1px dotted #d0cfcf;
}
</style>